<template>
  <view class="category-detail-list page-background">
    <CustomNavbar title="分类详情" :isBack="true" />
    <view class="content">
      <navigator
        v-for="(item,index) in classStore.categoryDetailList"
        :key="item._id+String(index)"
        :url="`/pages/preview/index?id=${item._id}`"
        open-type="navigate"
        hover-class="navigator-hover"
      >
        <u-image
          width="100%"
          height="540rpx"
          :src="item.smallPicurl"
          shape="square"
          border-radius="20rpx"
          mode="aspectFill"
        >
          <template #loading><u-loading /></template>
          <template #error><view style="font-size:24rpx">加载失败</view></template>
        </u-image>
      </navigator>
    </view>

    <u-loadmore
      bg-color="rgb(240,240,240)"
      :status="loadStatus"
      @loadmore="fetchCategoryData"
    />
    <u-back-top :scroll-top="scrollTop" />
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad, onReachBottom, onPageScroll } from '@dcloudio/uni-app'
import { useClassStore } from '@/stores/class'
import { getCategoryDetailAPI } from '@/api/class'
import { $u } from 'uview-pro'
import CustomNavbar from '../../components/UI/custom.vue'
/* ---------- 响应式 ---------- */
const loadStatus   = ref('loadmore')   // 底部状态
const isLoading    = ref(false)        // 接口锁
const scrollTop    = ref(0)

/* ---------- store ---------- */
const classStore = useClassStore()

/* ---------- 滚动 ---------- */
onPageScroll(e => scrollTop.value = e.scrollTop)

/* ---------- 核心：获取当前分类数据 ---------- */
const getCategoryDetail = async () => {
  try {
    const res = await getCategoryDetailAPI({
      classid : classStore.classid,
      pageNum : classStore.pageNum,
      pageSize: classStore.pageSize,
    })
    classStore.setTotal(res.total)
    classStore.addCategoryDetailList(res.data)
  } catch {
    $u.toast('好像出了点问题，刷新试试')
  }
}

/* ---------- 加载更多 ---------- */
const fetchCategoryData = async () => {
  if (isLoading.value || loadStatus.value === 'nomore') return
  isLoading.value = true
  classStore.pageNum++

  await getCategoryDetail()

  loadStatus.value =
    classStore.categoryDetailList.length >= classStore.total ? 'nomore' : 'loadmore'

  isLoading.value = false
}

/* ---------- 页面入口 ---------- */
onLoad(options => {
  const newId = options.classid

  /* 换了分类 -> 重置；同分类且本地有数据 -> 直接用 */
  if (newId !== classStore.classid) {
    classStore.classid = newId
    classStore.resetPagination()
  }

  /* 本地无数据才请求 */
  if (!classStore.categoryDetailList.length) getCategoryDetail()
})

/* ---------- 触底 ---------- */
onReachBottom(() => fetchCategoryData())
</script>

<style scoped lang="scss">
@import '@/common/style/page-background.scss';
.category-detail-list .content{
  display: grid;
  grid-template-columns: repeat(3,1fr);
  grid-gap: 5rpx;
}
</style>